package com.cyurs.netty.nettySimple.Http;

import com.sun.jndi.toolkit.url.Uri;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;


/**
 * SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter
 * 客户端和服务器端相互通讯的数据封装成 HttpObject
 */
public class TestHttpServerHandler  extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //判断发送来的msg是否是HttpRequest请求
        if (msg instanceof HttpRequest) {
            System.out.println("msg 类型 =" + msg.getClass());
            System.out.println("客户端地址：" + ctx.channel().remoteAddress());

            HttpRequest httpRequest = (HttpRequest) msg;
            //获取请求地址
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求的favicon不做响应！");
                return;
            }

            //回复消息给浏览器,并且设置编码
            //中文乱码请在UTF_8或UTF_16相互切换解决
            ByteBuf content = Unpooled.copiedBuffer("Hello,客户端!", CharsetUtil.UTF_16);
            //构造一个http响应，设置好版本号，状态及内容
            DefaultFullHttpResponse response =
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            //设置响应头 ，类型、长度
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            //将构建好的response返回
            ctx.writeAndFlush(response);
        }
    }
}
